package cn.imnu.legalaid.service.impl;

import cn.imnu.legalaid.dto.Lawyer.LawyerDetailDTO;
import cn.imnu.legalaid.dto.Lawyer.LawyerListDTO;
import cn.imnu.legalaid.dto.Lawyer.LawyerSearchDTO;
import cn.imnu.legalaid.entity.LawyerProfiles;
import cn.imnu.legalaid.entity.LawyerSpecialties;
import cn.imnu.legalaid.entity.User;
import cn.imnu.legalaid.mapper.LawyerProfilesMapper;
import cn.imnu.legalaid.mapper.LawyerSpecialtiesMapper;
import cn.imnu.legalaid.mapper.UsersMapper;
import cn.imnu.legalaid.service.LawyerProfilesService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class LawyerProfilesServiceImpl extends ServiceImpl<LawyerProfilesMapper, LawyerProfiles> 
    implements LawyerProfilesService {

    @Autowired
    private LawyerSpecialtiesMapper lawyerSpecialtiesMapper;
    
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public IPage<LawyerListDTO> getLawyerList(LawyerSearchDTO searchDTO) {
        Page<LawyerListDTO> page = new Page<>(searchDTO.getPage(), searchDTO.getPageSize());
        
        // 处理执业年限筛选
        Integer minExperience = null;
        Integer maxExperience = null;
        
        if (searchDTO.getExperienceFilter() != null && !searchDTO.getExperienceFilter().isEmpty()) {
            String[] range = searchDTO.getExperienceFilter().split("-");
            if ("10+".equals(searchDTO.getExperienceFilter())) {
                minExperience = 10;
            } else if (range.length == 2) {
                minExperience = Integer.parseInt(range[0]);
                maxExperience = Integer.parseInt(range[1]);
            }
        }
        
        IPage<LawyerListDTO> result = baseMapper.selectLawyerList(
            page,
            searchDTO.getSearchQuery(),
            searchDTO.getSpecialtyFilter(),
            minExperience,
            maxExperience,
            searchDTO.getSortBy()
        );
        
        // 为每个律师获取专业领域列表
        result.getRecords().forEach(lawyer -> {
            List<String> specialties = getLawyerSpecialties(lawyer.getId());
            lawyer.setSpecialties(specialties);
        });
        
        return result;
    }

    @Override
    public List<String> getAllSpecialties() {
        return baseMapper.selectAllSpecialties();
    }

    @Override
    public List<String> getLawyerSpecialties(Integer lawyerId) {
        QueryWrapper<LawyerSpecialties> wrapper = new QueryWrapper<>();
        wrapper.eq("lawyer_id", lawyerId);
        
        List<LawyerSpecialties> specialtyList = lawyerSpecialtiesMapper.selectList(wrapper);
        return specialtyList.stream()
                .map(LawyerSpecialties::getSpecialty)
                .collect(Collectors.toList());
    }

    @Override
    public LawyerDetailDTO getLawyerDetailByProfileId(Integer profileId) {
        // 1. 根据律师ID获取用户基本信息
        LawyerProfiles lawyerProfile = baseMapper.selectById(profileId);

        if (lawyerProfile == null) {
            return null;
        }

        // 2. 根据LawyerProfile中的user_id获取用户基本信息
        User user = usersMapper.selectById(lawyerProfile.getUser_id());
        if (user == null) {
            return null;
        }

        // 3. 构建律师详情DTO
        LawyerDetailDTO lawyerDetail = new LawyerDetailDTO();
        
        // 设置用户基本信息
        lawyerDetail.setId(lawyerProfile.getId());
        lawyerDetail.setRealName(user.getRealName());
        lawyerDetail.setEmail(user.getEmail());
        lawyerDetail.setPhone(user.getPhone());
        lawyerDetail.setAvatarUrl(user.getAvatarUrl());
        lawyerDetail.setLastLogin(user.getLastLogin());
        
        // 设置律师专业信息
        lawyerDetail.setBarNumber(lawyerProfile.getBar_number());
        lawyerDetail.setBarAssociation(lawyerProfile.getBar_association());
        lawyerDetail.setPracticeYears(lawyerProfile.getPractice_years());
        lawyerDetail.setFirmName(lawyerProfile.getFirm_name());
        lawyerDetail.setOfficeAddress(lawyerProfile.getOffice_address());
        lawyerDetail.setEducationBackground(lawyerProfile.getEducation_background());
        lawyerDetail.setProfessionalCertificates(lawyerProfile.getProfessional_certificates());
        lawyerDetail.setHourRate(lawyerProfile.getHour_rate());
        lawyerDetail.setRating(lawyerProfile.getRating());
        lawyerDetail.setCaseCount(lawyerProfile.getCase_count());
        lawyerDetail.setDescription(lawyerProfile.getDescription());
        lawyerDetail.setCreatedAt(lawyerProfile.getCreated_at());
        lawyerDetail.setUpdatedAt(lawyerProfile.getUpdated_at());
        
        // 4. 获取专业领域列表
        List<String> specialties = getLawyerSpecialties(lawyerProfile.getId());
        lawyerDetail.setSpecialties(specialties);
        
        return lawyerDetail;
    }
}




